package com.fan.leetcode;

import org.junit.jupiter.api.Test;

import java.util.Arrays;

/**
 * 704. 二分查找
 *
 * @author zhangFan
 * @since 2021/9/6 10:17
 */
public class Question704 {
    @Test
    void test() {
        System.out.println("search() = " + search(new int[]{-1, 0, 3, 5, 9, 12}, 2));
    }

    /**
     * 暴力解题
     * @param nums 整型数组
     * @param target 目标值
     * @return 目标值索引
     */
    /*public int search(int[] nums, int target) {
        int result = Arrays.binarySearch(nums, target);
        return result < 0 ? -1 : result;
    }*/
    public int search(int[] nums, int target) {
        int start = 0;
        int end = nums.length - 1;
        while (start <= end) {
            int middle = (start + end) / 2;
            int num = nums[middle];
            if (target > num) {
                start = ++middle;
            } else if (target < num) {
                end = --middle;
            } else {
                return middle;
            }
        }
        return -1;
    }
}
